<template>
  <div ref="formWrapper">
    <BasicTable @register="registerTable">
      <template #tableTitle>
        <Icon :icon="getTitle.icon" class="m-1 pr-1" />
        <span> 建筑管理 </span>
      </template>
      <template #toolbar>
        <a-button type="primary" @click="handleForm({})" v-auth="'unitmanage:unitBuilding:edit'">
          <Icon icon="i-fluent:add-12-filled" /> {{ t('新增') }}
        </a-button>
      </template>
      <template #firstColumn="{ record }">
        <a @click="handleForm({ tid: record.tid })">
          {{ record.enterpriseId }}
        </a>
      </template>
      <!-- 新增 action 插槽 -->
      <template #action="{ record }">
        <a-button @click="handleForm({ tid: record.tid })" v-auth="'unitmanage:unitBuilding:edit'" type="text">
          <span style="font-size:14px; color: #52c41a;">编辑</span>
        </a-button>
        <a-button @click="handleFormDetail({ tid: record.tid })"  type="text">
          <span style="font-size: 14px; color: #4169E1;">详情</span>
        </a-button>
        <a-button @click="handleFormFloor({ tid: record.tid })" v-auth="'unitmanage:unitFloor:edit'" type="text">
          <span style="font-size:14px; color: #528B8B;">楼层信息</span>
        </a-button>
        <Popconfirm
          title="是否确认删除建筑信息表"
          ok-text="确认"
          cancel-text="取消"
          @confirm="handleDelete(record)"
          @cancel="handleCancel"
        >
          <a-button @click="handleDelete(record)" v-auth="'unitmanage:unitBuilding:edit'" type="text" style="color: red;">
            <span style="font-size: 14px;">删除</span>
          </a-button>
        </Popconfirm>
      </template>
    </BasicTable>
    <InputForm @register="registerDrawer" @success="handleSuccess" />
    <FormDetail @register="registerDrawerDetail" @success="handleSuccess" />
    <FloorList @register="registerDrawerFloor" @success="handleSuccess" :tid="buildingId" />
  </div>
</template>

<script lang="ts" setup>
import { unref, ref, computed, watch, defineProps } from 'vue';
import { useI18n } from '/@/hooks/web/useI18n';
import { useMessage } from '/@/hooks/web/useMessage';
import { router } from '/@/router';
import { Icon } from '/@/components/Icon';
import { BasicTable, BasicColumn, useTable } from '/@/components/Table';
import { unitBuildingDelete, unitBuildingListData } from '/@/api/unitmanage/unitBuilding';
import { useDrawer } from '/@/components/Drawer';
import { FormProps } from '/@/components/Form';
import InputForm from './form.vue';
import FormDetail from './formDetail.vue';
import FloorList from './unitFloor/list.vue';
import { officeTreeData, officeListData } from '/@/api/sys/office';
import { unitFloorListData } from '/@/api/unitmanage/unitFloor';
import { Form, TreeSelect, SelectProps, Select, Button as AButton } from 'ant-design-vue';
import { unitEnterpriseDominantListData } from '/@/api/unitmanage/unitEnterpriseDominant';
import { Popconfirm } from 'ant-design-vue'; // 引入 Popconfirm 组件

const { t } = useI18n('unitmanage.unitBuilding');
const { showMessage } = useMessage();
const { meta } = unref(router.currentRoute);

const getTitle = {
  icon: meta.icon || 'i-ant-design:book-outlined',
  value: meta.title || t('建筑信息表管理'),
};

// 定义 props 接收 unitCode
const props = defineProps({
  unitCode: {
    type: String,
    default: ''
  }
})
const buildingName = ref('');

const EnterpriseParams = ref<Recordable>({
  name: '',
});

// 使用 computed 动态计算 params 对象
const selectParams = computed(() => {
  return {
    name: buildingName.value,
  };
});
const searchForm: FormProps = {
  baseColProps: { md: 8, lg: 6 },
  labelWidth: 90,
  schemas: [
    {
      label: t(''),
      field: 'unitCode',
      fieldLabel: 'enterpriseName',
      component: 'Select',
      componentProps: () => {
        return {
          placeholder: t('请输入主体名称'),
          api: unitEnterpriseDominantListData,
          params: EnterpriseParams.value,
          fieldNames: { label: 'name', value: 'unitCode' },
          resultField: 'list',
          notFoundContent: '未查询到记录',
          allowClear: true,
          filterTreeNode: false,
          filterOption: false,
          immediate: true,
          onSearch: (value: string) => {
            EnterpriseParams.value.name = value;
            console.log(EnterpriseParams.value);
          },
        };
      },
    },
    {
      label: t(''),
      field: 'id',
      fieldLabel: 'name',
      component: 'TreeSelect',
      componentProps: {
        placeholder: t('请输入建筑名称'),
        api: unitBuildingListData,
        params: selectParams,
        resultField: 'list',
        fieldNames: { label: 'name', value: 'id' },
        allowClear: true,
        immediate: false,
        each: false,
        showSelect: true,
        optionFilterProp: 'label',
        showSearch: true,
        onSearch: (value) => {
          buildingName.value = value;
          // console.log('输入的值:', value);
          reload();
        },
      },
    },
  ],
};

const tableColumns: BasicColumn[] = [
  {
    title: t('主体名称'),
    dataIndex: 'enterpriseName',
    key: 'a.enterprise_name',
    sorter: true,
    width: 130,
    align: 'left',
  },
  {
    title: t('建筑名称'),
    dataIndex: 'name',
    key: 'a.name',
    sorter: true,
    width: 130,
    align: 'left',
  },
  {
    title: t('详细地址'),
    dataIndex: 'location',
    key: 'a.location',
    sorter: true,
    width: 130,
    align: 'left',
  },
  {
    title: t('操作'),
    dataIndex: 'action',
    key: 'action',
    width: 160,
    slot: 'action' // 指定使用 action 插槽
  }
];

const [registerTable, { reload }] = useTable({
  api: unitBuildingListData,
  beforeFetch: async (params) => {
    const route = unref(router.currentRoute);
    const unitCode = route.query.unitCode;
    if (unitCode) {
      params.unitCode = unitCode;
    }
    return params;
  },
  columns: tableColumns,
  // actionColumn: actionColumn, // 移除原有的 actionColumn 配置
  formConfig: searchForm,
  showTableSetting: true,
  useSearchForm: true,
  canResize: true,
});

const [registerDrawer, { openDrawer }] = useDrawer();
const [registerDrawerDetail, { openDrawer: openDrawerDetail }] = useDrawer();
const [registerDrawerFloor, { openDrawer: openDrawerFloor }] = useDrawer();

function handleForm(record) {
  openDrawer(true, record);
}

function handleFormDetail(record) {
  openDrawerDetail(true, record);
}

const buildingId = ref<number | null>(null);

async function handleFormFloor(record) {
  buildingId.value = record.tid;
  openDrawerFloor(true, record);
}

async function handleDelete(record: Recordable) {
  const params = { tid: record.tid };
  const res = await unitBuildingDelete(params);
  showMessage(res.message);
  handleSuccess(record);
}

function handleSuccess(record) {
  reload({ record });
}

function handleCancel() {
  console.log('取消删除操作');
}
</script>